﻿using System.Diagnostics;
using System.Linq;

namespace Quail
{
    public static class StackHelper
    {
        /// <summary>
        /// Returns the name of a method in the stack.  By default, it returns the name of the method calling your method.
        /// </summary>
        /// <param name="frameOffset">Method in the stack trace to return.  0 == your method, 1 == the method calling you, etc.</param>
        /// <returns>The name of the method</returns>
        public static string GetCallingMethodName(int frameOffset = 0)
        {
            return GetCallingMethodName(false, frameOffset + 1);
        }

        /// <summary>
        /// Returns the name of a method in the stack.  By default, it returns the name of the method calling your method.
        /// </summary>
        /// <param name="includeClassName">Include the name of the class in the result</param>
        /// <param name="frameOffset">Method in the stack trace to return.  0 == your method, 1 == the method calling you, etc.</param>
        /// <returns>The name of the method</returns>
        public static string GetCallingMethodName(bool includeClassName, int frameOffset = 0)
        {
            StackFrame[] frames = new StackTrace().GetFrames();
            if (frames == null)
                return string.Empty;

            var frame = frames[frameOffset + 1];
            var method = frame.GetMethod();
            if (includeClassName)
                return method.ReflectedType.Name + "." + method.Name;

            return method.Name;
        }
    }
}
